package top.yxqz.servlet;

import top.yxqz.school.Student;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

/**
 * @author Mr.余
 * @package top.yxqz.servlet
 * 登录功能实现
 */
public class LoginServletDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context  = getServletContext();
        //        解决中文乱码问题
        String req_encoding = context.getInitParameter("req_encoding");
        String resp_encoding = context.getInitParameter("resp_encoding");
        req.setCharacterEncoding(req_encoding);
        resp.setContentType(resp_encoding);

        //        获取前端属性
        String username = req.getParameter("username");
        String password = req.getParameter("password");
//        String userName  = "yxqz";
//        String pwd = "123321";

//        获取集合中的数据 从注册的Servlet中
//
//        ZhuCeServlet zhuCeServlet = new ZhuCeServlet();
//        ArrayList<Student> students = zhuCeServlet.getStudents();
//        System.out.println("students"+students.get(0));

//        ArrayList<Student> students =  ZhuCeServlet.students;
        ArrayList<Student> students = (ArrayList<Student>) context.getAttribute("students");
        for (Student stu:students
             ) {
            String userName = stu.getName();
            String pwd = stu.getPassword();
            if (userName.equals(username) && pwd.equals(password)){
                PrintWriter writer = resp.getWriter();
                writer.print("welcome:"+username);
            }

        }


    }
}
